from django.contrib.auth import authenticate, logout, login
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
import traceback
import json
import random
from django.shortcuts import get_object_or_404
from django.urls import reverse

from server.models import Project,Label
from server.serializers import LabelSerializer,RelationLabelSerializer,AttributeLabelSerializer

from rest_framework.permissions import IsAuthenticated,IsAdminUser
from .permissions import IsProjectUser
from rest_framework.views import APIView
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema



class GetUrl(APIView):
    permission_classes = []

    @swagger_auto_schema(operation_summary='获得session存储的系统的url')
    def get(self,request,*args,**kwagrs):
        return getUrl(request)

class AutoLogin(APIView):
    permission_classes = []

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['username', 'password'],
        properties={'username': openapi.Schema(type=openapi.TYPE_STRING),
                    'password': openapi.Schema(type=openapi.TYPE_STRING)}
    ), operation_summary='自动登录')
    def post(self,request,*args,**kwargs):
        return auto_login(request)

class AutoRegister(APIView):
    permission_classes = []

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['username', 'password'],
        properties={'username': openapi.Schema(type=openapi.TYPE_STRING),
                    'password': openapi.Schema(type=openapi.TYPE_STRING)}
    ), operation_summary='注册')
    def post(self,request,*args,**kwargs):
        return auto_register(request)

class Login(APIView):
    permission_classes = []

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['username', 'password'],
        properties={'username': openapi.Schema(type=openapi.TYPE_STRING),
                    'password': openapi.Schema(type=openapi.TYPE_STRING)}
    ), operation_summary='登录')
    def post(self, request, *args, **kwargs):
        username = request.data["username"]
        password = request.data["password"]

        if username and password:
            user = authenticate(username=username, password=password)
            if User.objects.filter(username=username):
                # "用户已存在"
                if user:
                    login(request, user)
                    return HttpResponse(200)
                else:
                    return HttpResponse("密码错误", status=301)
            else:
                return HttpResponse("用户不存在",status=301)
        else:
            return HttpResponse("参数错误", status=302)

class Logout(APIView):
    permission_classes =  [IsAdminUser]

    def get(self,request,*args,**kwargs):
        try:
            logout(request)
            return HttpResponse(200)
        except:
            return HttpResponse(302)

class AddLabel(APIView):
    permission_classes = (IsAuthenticated, IsProjectUser)

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['labels','relations','attributes'],
        properties={'labels': openapi.Schema(type=openapi.TYPE_ARRAY,items=openapi.Items(type=openapi.TYPE_STRING)),
                    'relations':openapi.Schema(type=openapi.TYPE_ARRAY,items=openapi.Items(type=openapi.TYPE_STRING)),
                    'attributes':openapi.Schema(type=openapi.TYPE_ARRAY,items=openapi.Items(type=openapi.TYPE_ARRAY,
                                                                    items=openapi.Items(type=openapi.TYPE_STRING)))}
    ), operation_summary='从图谱导入标签')
    def post(self,request,*args,**kwagrs):
        project_id=self.kwargs['project_id']
        return add_label(request,project_id)


def getUrl(request):
    response = HttpResponse(content_type='text/json')
    try:
        url = request.session["url"]
    except Exception as e:
        print(e)
        url ="hengshui.askgraph.xyz"
        print("excpetion in url")
    print("url is " +url)
    response.write(url)
    return response

def auto_login(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    #data = json.loads(request.body.decode())
    data=request.data
    print(data)
    username = data["username"]
    password = data["password"]

    if username and password:
        user = authenticate(username=username, password=password)
        if User.objects.filter(username=username):
            # "用户已存在"
            if user:
                login(request, user)
                return HttpResponse(200)
            else:
                return HttpResponse("该用户已经存在,密码错误", status=301)
        else:
            #用户不存在 进行注册
            rsp = auto_register(request)
            if rsp.status_code != 200:
                return HttpResponse("注册失败", status=304)
            else:
                user = authenticate(username=username, password=password)
                login(request, user)
                return HttpResponseRedirect(reverse("projects"))
    else:
        return HttpResponse("参数错误", status=302)


def auto_register(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    #data = json.loads(request.body.decode())
    data = request.data
    username = data["username"]
    password = data["password"]
    if username and password:
        try:
            User.objects.create_superuser(username=username, password=password, email='')
        except Exception as e:
            return HttpResponse("注册失败", status=500)
        else:
            return HttpResponse("注册成功", status=200)

    else:
        return HttpResponse("参数错误", status=302)

def add_label(request,project_id):
    if request.method != 'POST':
        return HttpResponse(status=404)
    #data = json.loads(request.body)
    data = request.data
    label_list = data["labels"]
    relation_list=data["relations"]
    attribute_list=data["attributes"]
    print(label_list,relation_list,attribute_list)
    project = get_object_or_404(Project,pk=project_id)

    colorArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    data = {'shortcut': None, 'text_color': '#ffffff'}
    for label in label_list:
        data['text'] = str(label)
        color = ""
        for i in range(6):
            color += colorArr[random.randint(0, 14)]
        data['background_color'] = "#" + color
        try:
            ls = LabelSerializer(data=data)
            ls.is_valid()
            ls.save(project=project)
        except:
            print("this label has in")
            continue
    data=dict()
    for relation in relation_list:
        data['relation_name']=str(relation)
        try:
            rls=RelationLabelSerializer(data=data)
            rls.is_valid()
            rls.save(project=project)
        except:
            print("relation label already exist!")
            continue
    data=dict()
    for attribute in attribute_list:
        data['attribute_name']=attribute[1]
        try:
            label = get_object_or_404(Label, text=attribute[0])
            als = AttributeLabelSerializer(data=data)
            als.is_valid()
            als.save(label=label)
        except:
            print("attribute label already exist!")
            continue

    return HttpResponse("添加成功",status=200)
